<template src="./supplierUser.html"></template>

<script>
  import {
    getSupplierCustomer,
    updateServicesHistory,
    getServicesConsumeHistory,
    getServicesBySupplierID,
    createServicesHistory,
    getSpecServices
  } from '../../../api/supplierManagement/supplierUser'
  import {getService} from '@/api/supplierManagement/project'
  import {getSupplier} from '@/api/supplierManagement/supplier'
  import {parseTime} from '@/utils/ruoyi'
  import Pagination from '@/components/Pagination'
  import moment from "moment";

  export default {
    name: 'SupplierUser',
    components: {Pagination},
    // computed: {
    //   ...mapGetters(["defaultSupplierID"]),
    // },
    data() {
      return {
        list: null,
        total: 0,
        listLoading: false,
        listQuery: {
          pageNum: 1,
          pageSize: 10,
          custName: null,
          certID: null,
          usedStatus: null,
          supplierID: null,
          serviceID: null
        },
        ruleForm1: {verificationList: []},
        rules1: {
          serviceID: [{required: true, message: "请选择服务名称", trigger: "change"}],
          consumeTime: [{required: true, message: "请选择使用时间", trigger: "change"}],
          numConsumed: [
            {required: true, message: '请输入次数', trigger: "blur"},
            {type: 'number', message: '次数必须为数字值'}
          ]
        },
        ruleForm: {
          listRow: [{
            customerID: '',
            serviceID: '',
            supplierID: '',
            custServiceNum: '',
            consumeTime: '',
            remarks: '',
            numConsumed: ''
          }],
        },
        rules: {
          serviceID: [{required: true, message: "请选择服务名称", trigger: "change"}],
          consumeTime: [{required: true, message: "请选择使用时间", trigger: "change"}],
          numConsumed: [
            {required: true, message: '请输入次数', trigger: "blur"},
            {type: 'number', message: '次数必须为数字值'}
          ]
        },
        ServicesHistoryQuery: {
          custServiceNum: null,
          customerID: null,
          supplierID: null
        },
        defaultSupplierID: null,
        customerID: null,
        supplierID: null,
        writeoOffVisible: false,
        statusOptions: [
          {label: '已使用', value: 1},
          {label: '未使用', value: 0}
        ],
        supplierOptions: [],
        serviceNameOptions: [],
        supplierServices: [],
        currentEquity: null,
        downloading: false,
        hidePrivate: false
      }
    },
    async created() {
      this.hidePrivate = localStorage.getItem('hidePrivate') === '1';
      const supplierID = localStorage.getItem('supplierID');
      this.defaultSupplierID = supplierID;
      this.listQuery.supplierID = supplierID;
      // console.log('default id:::', this.defaultSupplierID);
      await getSupplier().then(res => {
        this.supplierOptions = res
      })
      this.getServiceOptions();
      // this.list = this.pageInfo.list
      // this.total = this.pageInfo.total
      // this.getList()
    },
    methods: {
      filterPhoneNumber({phoneNumber}) {
        if (!phoneNumber) {
          return '';
        }
        if (!this.hidePrivate) {
          return phoneNumber;
        } else {
          return phoneNumber.substr(0, 3) + '****' + phoneNumber.substr(7);
        }
      },
      formatDate(timeStr) {
        if (!timeStr) {
          return '';
        }
        return moment(timeStr).format('YYYY-MM-DD');
      },
      handleSupplierChange() {
        console.log('supplier changed....');
        this.listQuery.serviceID = null;
        this.getServiceOptions();
      },
      getServiceOptions() {
        if (this.listQuery.supplierID) {
          getServicesBySupplierID(this.listQuery.supplierID).then(resp => {
            this.serviceNameOptions = resp;
          });
        } else {
          getService().then(resp => {
            this.serviceNameOptions = resp;
          })
        }
      },
      getList() {
        if (!this.listQuery.supplierID) {
          this.$message.error("请选择供应商");
          return;
        }
// console.log('query:::', this.listQuery);
        this.listLoading = true;
        let query = {...this.listQuery};
        query.page = this.listQuery.pageNum - 1;
        query.size = this.listQuery.pageSize;
        query.sort = 'cu.custName';
        query.identity = this.listQuery.certID;
        query.customerName = this.listQuery.custName;

        getSupplierCustomer(query).then(response => {
          this.listLoading = false
          this.list = response.content
          this.total = response.totalElements
        }).catch(() => {
          this.listLoading = false
        })
      },

      // 查询
      listSearch() {
        this.listQuery.pageNum = 1
        this.getList()
      },

      exportList() {

        // let user = JSON.parse(localStorage.getItem('user'));
        let url = process.env.VUE_APP_BASE_API + '/excel/downloadSupplierCust?hidePrivate=' + this.hidePrivate;
        if (this.listQuery.custName) {
          url += `&custName=${this.listQuery.custName}`;
        }
        if (this.listQuery.supplierID) {
          url += `&supplierID=${this.listQuery.supplierID}`;
        }
        if (this.listQuery.serviceID) {
          url += `&serviceID=${this.listQuery.serviceID}`;
        }
        if (this.listQuery.certID) {
          url += `&certID=${this.listQuery.certID}`;
        }
        if (this.listQuery.usedStatus) {
          url += `&usedStatus=${this.listQuery.usedStatus}`;
        }
// console.log('url:::', url);
        // let objectUrl = URL.createObjectURL(url)
        const link = document.createElement('a')
        // link.download = fileName
        link.href = url
        link.target = '_blank';
        link.click()
      },

      // 核销
      async handleWriteOff(row) {
        this.currentEquity = row;
        this.ruleForm1.verificationList = []
        this.ServicesHistoryQuery = {
          custServiceNum: row.custServiceNum,
          customerID: row.customerID,
          supplierID: row.supplierID
        }
        console.log('current row data:::', row);
        // 根据当前参数(supplierID)重新获取服务内容
        // if (row.supplierID) {
        let query = {
          equityID: row.equityID,
          equityLevelID: row.equityLevelID
        }
        if (row.supplierID) {
          query.supplierID = row.supplierID;
        }
        if (localStorage.getItem('supplierID')) {
          query.supplierID = localStorage.getItem('supplierID');
        }

        await getSpecServices(query).then(resp => {
          this.supplierServices = resp;
        });
        // } else {
        //   this.supplierServices = this.serviceNameOptions;
        // }

        this.getVerification(row);
        this.writeoOffVisible = true
      },

      // 获取流水
      getVerification(row) {
        console.log('row here:::1', row);
        // debugger;
        let query = {
          customerID: row.customerID,
          equityID: row.equityID,
          equityLevelID: row.equityLevelID
        }
        console.log('row here:::2', row);
        // getServicesConsumeHistory(this.ServicesHistoryQuery).then(response => {
        getServicesConsumeHistory(query).then(response => {
          this.ruleForm = {
            listRow: [{
              customerID: '',
              serviceID: '',
              supplierID: '',
              custServiceNum: '',
              consumeTime: '',
              remarks: '',
              numConsumed: ''
            }]
          }
          if (response.length > 0) {
            response.forEach(item => {
              item.consumeTime = parseTime(item.consumeTime, '{y}/{m}/{d}')
            });
            let list = [];
            response.forEach(r => {
              if (this.supplierServices.find(s => s.serviceID === r.serviceID)) {
                list.push(r);
              }
            })
            this.ruleForm1.verificationList = list;
          } else {
            this.ruleForm1.verificationList = []
          }
        })
      },

      // 新增流水
      addVerification(row, formName) {
        console.log(row, this.currentEquity);
        this.$refs[formName].validate(valid => {
          if (valid) {
            row.equityTableID = this.currentEquity.id;
            row.custServiceNum = this.ServicesHistoryQuery.custServiceNum;
            row.serviceID = this.currentEquity.serviceID;
            row.customerID = this.ServicesHistoryQuery.customerID;
            row.supplierID = this.ServicesHistoryQuery.supplierID;
            row.consumeTime = parseTime(row.consumeTime, '{y}-{m}-{d} {h}:{i}:{s}');
            row.equityID = this.currentEquity.equityID;
            row.equityLevelID = this.currentEquity.equityLevelID;

            createServicesHistory(row).then(resp => {
              this.msgSuccess("操作成功");
              this.getVerification(this.currentEquity);
            });
            // saveServicesHistory(row).then(response => {
            //   this.msgSuccess("操作成功");
            //   this.getVerification()
            // })
          } else {
            return false;
          }
        });
      },

      // 修改流水
      updateVerification(row, formName) {
        console.log(row)
        row.consumeTime = parseTime(row.consumeTime, '{y}-{m}-{d} {h}:{i}:{s}')
        this.$refs[formName].validate(valid => {
          if (valid) {
            row.equityTableID = this.currentEquity.id;
            updateServicesHistory(row).then(response => {
              if (response.status == 'SUCCESS') {
                this.msgSuccess("操作成功");
                // this.getVerification()
              }
            })
          } else {
            return false;
          }
        });
      },

      // 关闭
      closeWriteoOffVisible() {
        this.writeoOffVisible = false;
        this.getList();
      },

      statusFormatter(row) {
        let status = '未使用'
        if (row.usedCount > 0) {
          status = '已经使用'
        }
        return status
      },
    }
  }
</script>
<style lang="scss" scoped src="./supplierUser.scss"></style>
